﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using Business;


public partial class User_Shares_ExcelOutput : System.Web.UI.Page
{

    private int _AdvisorDelay;
    public int AdvisorDelay
    {
        get { return _AdvisorDelay; }
        set
        {
            _AdvisorDelay = value;
        }
    }

    private int _FourthFactorDelay;
    public int FourthFactorDelay
    {
        get { return _FourthFactorDelay; }
        set
        {
            _FourthFactorDelay = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ContractIds"] != null)
        {
            var datasource = ExcelOutput.ExcelOutputMaker((List<Guid>)Session["ContractIds"]);
            Session["ContractIds"] = null;
            GridView gridVillage, gridContractInfo, gridProjectStatus;

            GridViewExcelOutput.DataSource = datasource;
            List<ExcelType> datasourceRow;
            GridViewExcelOutput.DataBind();
            Panel firstRow;
            List<int> delays = new List<int>();
            for (int i = 0; i < GridViewExcelOutput.Rows.Count; i++)
            {
                gridVillage = GridViewExcelOutput.Rows[i].FindControl("GridViewVillage") as GridView;
                gridContractInfo = GridViewExcelOutput.Rows[i].FindControl("GridViewContractInfo") as GridView;
                gridProjectStatus = GridViewExcelOutput.Rows[i].FindControl("GridViewProjectStatus") as GridView;
                // firstRow = GridViewExcelOutput.Rows[ 0 ].FindControl( "PanelFirstRow" ) as Panel;
                //gridDataEnterGuy = GridViewExcelOutput.Rows[i].FindControl("GridViewDataEnterGuy") as GridView;

                Guid contractId;
                if (GridViewExcelOutput.DataKeys != null)
                {
                    contractId = new Guid(GridViewExcelOutput.DataKeys[i].Value.ToString());
                    datasourceRow = ExcelOutput.ExcelOutputRow(contractId);
                    if (gridVillage != null)
                    {
                        gridVillage.DataSource = datasourceRow;
                        gridVillage.DataBind();
                    }

                    if (gridContractInfo != null)
                    {
                        gridContractInfo.DataSource = datasourceRow;
                        gridContractInfo.DataBind();
                    }

                    if (gridProjectStatus != null)
                    {
                        int count = CommonCalculations.StepsCount(contractId);
                        int numberOfEnteredFields = CommonCalculations.CountEnteredTasks(contractId);
                        if (count > numberOfEnteredFields)
                        {
                            delays = ColumnsMaker(numberOfEnteredFields, datasourceRow, gridProjectStatus);
                            var allSteps = CommonCalculations.GetAllSteps(contractId);
                            for (int j = numberOfEnteredFields + 1; j < count; j++)
                            {
                                TemplateField templateField = new TemplateField();
                                templateField.ItemTemplate = new TemplateHandler("--", "--", "--", "--", "--");
                                templateField.HeaderText = allSteps[j];
                             
                                gridProjectStatus.Columns.Add(templateField);
                            }
                        }
                        else if (count <= numberOfEnteredFields)
                        {
                            delays = ColumnsMaker(numberOfEnteredFields, datasourceRow, gridProjectStatus);
                        }
                        gridProjectStatus.DataSource = datasourceRow;
                        gridProjectStatus.Width = count * 150;
                        gridProjectStatus.HeaderStyle.Width = 150;
                        //firstRow.Height = 120;
                        gridProjectStatus.DataBind();
                        AdvisorDelay = delays[0];
                        FourthFactorDelay = delays[1];
                        Label fourthfactorLabel = GridViewExcelOutput.Rows[i].FindControl("LabelFourthFactor") as Label;
                        Label advisorLabel = GridViewExcelOutput.Rows[i].FindControl("LabelAdvisor") as Label;
                        if (fourthfactorLabel != null)
                            fourthfactorLabel.Text = string.Format("میزان دیرکرد عامل جهار:{0} روز", FourthFactorDelay);
                        if (advisorLabel != null)
                            advisorLabel.Text = string.Format("میزان دیرکرد مشاور / نقشه بردار:{0} روز", AdvisorDelay);
                        gridProjectStatus.HeaderRow.Attributes["id"] = "equalize";
                      
                    }
                }
            }
        }
    }


    private static List<int> ColumnsMaker(int upperLimit, List<ExcelType> datasourceRow, GridView gridProjectStatus)
    {
        List<int> outputDelay = new List<int>();
        foreach (var excelType in datasourceRow)
        {
            excelType.Tasks = excelType.Tasks.OrderBy(task => task.StepPriority).ToList();


            for (int j = 0; j < excelType.Tasks.Count - 1; j++)
            {
                var task = excelType.Tasks[j];
                if (task.HasRepeat)
                {
                    int startIndex = task.PreviousStep;
                    int counter = 0;
                    int endIndex = task.StepPriority;
                    foreach (var t in excelType.Tasks)
                    {
                        if (t.StepPriority == startIndex)
                        {
                            startIndex = counter;
                            break;
                        }
                        counter++;
                    }
                    counter = 0;
                    foreach (var t in excelType.Tasks)
                    {
                        if (t.StepPriority > endIndex)
                        {
                            endIndex = counter;
                            break;
                        }
                        counter++;
                    }

                    CompareProjectStatusTaskType comp = new CompareProjectStatusTaskType();
                    excelType.Tasks.Sort(startIndex, endIndex - startIndex, comp);
                }
            }
        }

        int advisorDelay = 0, fourthFactorDelay = 0;
        for (int i = 0; i < upperLimit; i++)
        {
            TemplateField templateField = new TemplateField();
            var item = datasourceRow[0].Tasks[i];
            if (!item.HasRepeat)
            {
                switch (item.InputGuy)
                {
                    case InputGuyType.InputGuy.Advisor:
                        templateField.ItemTemplate = new TemplateHandler(item.DateDoneFarsi, "--", "--", "--", item.Latency.ToString());
                        advisorDelay += item.Latency;
                        break;
                    case InputGuyType.InputGuy.BonyadeShahrestan:
                        templateField.ItemTemplate = new TemplateHandler("--", "--", item.DateDoneFarsi, "--", item.Latency.ToString());
                        break;
                    case InputGuyType.InputGuy.Employer:
                        templateField.ItemTemplate = new TemplateHandler("--", item.DateDoneFarsi, "--", "--", item.Latency.ToString());
                        break;
                    case InputGuyType.InputGuy.FourthFactor:
                        templateField.ItemTemplate = new TemplateHandler("--", "--", "--", item.DateDoneFarsi, item.Latency.ToString());
                        fourthFactorDelay += item.Latency;
                        break;
                    default:
                        templateField.ItemTemplate = new TemplateHandler(item.DateDoneFarsi, "--", "--", "--", item.Latency.ToString());
                        break;
                }
            }
            //reduce size of header string
            //if (item.StepName.Length > 35)
            //{
            //    string tempString = item.StepName;
            //    tempString = tempString.Substring( 0, tempString.IndexOf(" ", 30)) + "...";
            //    item.StepName = tempString;
            //}
            templateField.HeaderText = item.StepName;
            templateField.HeaderStyle.Wrap = true;
            templateField.HeaderStyle.Font.Bold = true;

            gridProjectStatus.Columns.Add(templateField);

            outputDelay.Add(advisorDelay);
            outputDelay.Add(fourthFactorDelay);
          
        }
        return outputDelay;
    }

    protected void ExportToExcel_Click(object sender, EventArgs e)
    {

        try
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = System.Text.Encoding.Unicode;
            Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            //this.EnableViewState = false;
           
            StringWriter sr = new StringWriter();
            HtmlTextWriter hr = new HtmlTextWriter(sr);
            GridViewExcelOutput.RenderControl(hr);
            Response.Write(sr.ToString());
            sr.Dispose();
            hr.Dispose();
            Response.End();        

        }
        catch (Exception ex)
        {
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }


    protected void ExportToWord_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
            Response.ContentType = "application/vnd.word";
            Response.ContentEncoding = System.Text.Encoding.Unicode;
            Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            //this.EnableViewState = false;
            StringWriter sr = new StringWriter();
            System.Web.UI.HtmlTextWriter hr = new HtmlTextWriter(sr);
            GridViewExcelOutput.RenderControl(hr);
            Response.Write(sr.ToString());
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            sr.Dispose();
            hr.Dispose();
            Response.End();
        }
        catch (Exception ex)
        {
        }

    }
    //protected void btnPrint_Click(object sender, EventArgs e)
    //{
    //    StringWriter sw = new StringWriter();

    //    HtmlTextWriter hw = new HtmlTextWriter(sw);

    //    GridViewExcelOutput.RenderControl(hw);

    //    string gridHTML = sw.ToString().Replace("\"", "'")

    //        .Replace(System.Environment.NewLine, "");

    //    StringBuilder sb = new StringBuilder();

    //    sb.Append("<script type = 'text/javascript'>");

    //    sb.Append("window.onload = new function(){");

    //    sb.Append("var printWin = window.open('', '', 'left=0");

    //    sb.Append(",top=0,width=1000,height=600,status=0');");

    //    sb.Append("printWin.document.write(\"");

    //    sb.Append(gridHTML);

    //    sb.Append("\");");

    //    sb.Append("printWin.document.close();");

    //    sb.Append("printWin.focus();");

    //    sb.Append("printWin.print();");

    //    sb.Append("printWin.close();};");

    //    sb.Append("</script>");

    //    ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());



    //}
}